// pages/order/order.js
import api from '../../utils/api' // 引入api接口管理文件
import {throttle} from '../../utils/util'

const app = getApp()
Page({
  onLoad: function(options) {
    let data = getApp().globalData.chooseDetail
    this.setData({
      chooseDetail: data,
      price: data.chooseType.payPrice,
      totalPrice: data.chooseType.payPrice * this.data.number,
      isFullSucreen: getApp().globalData.isFullSucreen
    }, () => {
      this.showOrderRead()
    })
  },
  /**
   * 页面的初始数据
   */
  data: {
    checkedAgree: false,
    number: 1,
    totalPrice: 0,
    price: 0,
    chooseDetail: {},
    orderNo: null,
    isFullSucreen: false,
    showDialog: false
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  radioChange(e) {
    this.setData({
      checkedAgree: !this.data.checkedAgree
    })
  },
  reduceNum() {
    if (this.data.number > 1) {
      this.setData({
        number: this.data.number - 1,
        totalPrice: (this.data.price * (this.data.number - 1)).toFixed(2)
      })
    }
  },
  addNum() {
    this.setData({
      number: this.data.number + 1,
      totalPrice: (this.data.price * (this.data.number + 1)).toFixed(2)
    })
  },
  inputChange (e) {
    if (e.detail.value >= 1) {
      this.setData({
        number: e.detail.value * 1,
        totalPrice: (this.data.price * e.detail.value).toFixed(2)
      })
    } else {
      this.setData({
        number: 1,
        totalPrice: (this.data.price * 1).toFixed(2)
      })
    }
  },
  showOrderRead () {
    if (this.data.chooseDetail.chooseType.prePayWarn && this.data.chooseDetail.chooseType.prePayWarn  !== '') {
      this.setData({
        showDialog: true
      })
      return
    }

    // this.createdOrder()
  },
  alreadyRead () {
    // this.createdOrder()
    this.cancelDiaglog()
  },
  cancelDiaglog () {
    this.setData({
      showDialog: false
    })
  },
  createdOrder () {
    const that = this
    const { channel } = app.globalData || {}
    console.log('app.globalData: ', app.globalData);

    if (!wx.getStorageSync('token')) {
      throttle(function (e) {
        wx.navigateTo({
          url: `../login/login`
        })
      }, 2000)
      return
    }
    
    api.orderSubmit({
      data: {
        num: this.data.number,
        productId: this.data.chooseDetail.productId,
        productMirrorId: this.data.chooseDetail.chooseType.id,
        orderType: 7,
        orderSource: +channel ? +channel : 4,
        cusImuid: wx.getStorageSync('customerUid') || '',
      },
      success: res => {
        if (res.code * 1 === 0) {
          let orderNo = res.data.orderNo
          that.setData({
            orderNo: orderNo
          })
          that.payAppWeChatPay(orderNo)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error'
          })
        }
      }
    })
  },
  payAppWeChatPay (orderNo) {
    const that = this
    api.payAppWeChatPay({
      data: {
        payChannelId: 1,
        orderNo: orderNo, //订单号
        appid: "wxff3fc00494f4f0e3", //应用APPID
        body: that.data.chooseDetail.name,//商品描述
        detail: "", //商品详情信息
        fee_type: "CNY", //币种，默认人民币
        limit_pay: "" //默认空，上传此参数no_credit--可限制用户不能使用信用卡支付
      },
      success: res => {
        if (res.code * 1 === 0) {
          wx.requestPayment({
            timeStamp: res.data.timeStamp + '',
            nonceStr: res.data.nonceStr,
            package: res.data.packageStr,
            signType: 'MD5',
            paySign: res.data.paySign,
            success (res) {
              throttle(function (e) {
                wx.redirectTo({
                  url: `../appointment/appointment?index=-100`
                })
              }, 2000 )
            },
            fail (fail) { 
              throttle(function (e) {
                wx.redirectTo({
                  url: `../appointment/appointment?index=0`
                })
              }, 2000 )
            }
          })
        }
      }
    })
  },
  moveTo () {
    throttle(function (e) {
      wx.navigateTo({
        url: `../agreement/agreement`
      })
    }, 2000) 
  }
})